import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:lcapp/api/interface/user_api.dart';
import 'package:lcapp/api/request/response_data.dart';
import 'package:lcapp/data/user_data_entity.dart';
import 'package:lcapp/model/refresh/refresh.dart';
import 'package:lcapp/page/search/search_user_item.dart';

class SearchUserPage extends StatefulWidget {
  final String searchValue;
  const SearchUserPage({Key? key, required this.searchValue}) : super(key: key);

  @override
  _SearchUserPageState createState() => _SearchUserPageState();
}

class _SearchUserPageState extends State<SearchUserPage> {
  int pageNum = 1;
  int pageSize  =10;
  List<UserDataEntity> users = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getSearchResults();
  }

  @override
  void didUpdateWidget(covariant SearchUserPage oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
    if(oldWidget.searchValue != widget.searchValue){
      pageNum = 1;
      getSearchResults();
    }
  }

  getSearchResults()async{
    ResponseData res = await UserAPI.searchUsers(widget.searchValue,pageNum,pageSize);
    if(res.code==200){
      if(pageNum==1){
        users.clear();
      }
      List arr = res.data??[];
      for (var element in arr) {
        UserDataEntity entity = UserDataEntity().fromJson(element);
        users.add(entity);
      }
    }
    if(mounted){setState(() {
    });}
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh(
      footer: myRefreshFooter(),
      header: myRefreshHeader(),
      onRefresh: ()async{
        pageNum=1;
        getSearchResults();
      },
      onLoad: ()async{
        pageNum++;
        getSearchResults();
      },
      child: ListView.builder(
          padding: EdgeInsets.zero,
          shrinkWrap: true,
          itemCount: users.length,
          itemBuilder: (BuildContext context, int i) {
            return SearchUserItem(entity: users[i],cilickFun: (){
              Navigator.of(context).pushNamed("ShopHomePage",arguments: users[i].id);
            },);
          }),
    );
  }
}
